package com.drinks.yiniang.ui.fragment.community.user;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.drinks.yiniang.R;
import com.drinks.yiniang.adapter.community.UCShareAdapter;
import com.drinks.yiniang.common.recycler.decoration.ItemSpacesDecoration;
import com.drinks.yiniang.entity.comment.CommentSubmitJson;
import com.drinks.yiniang.entity.common.StringJson;
import com.drinks.yiniang.entity.community.CommunityNewsJson;
import com.drinks.yiniang.io.api.CommunityApiIO;
import com.drinks.yiniang.ui.activity.community.CommunityCommentsActivity;
import com.drinks.yiniang.ui.widget.dialog.CommentBoxDialog;
import com.drinks.yiniang.ui.widget.dialog.ShareDialog;
import com.drinks.yiniang.ui.widget.recycler.BaseRecyclerView;
import com.drinks.yiniang.utils.ActivityUtils;
import com.hansen.library.ui.widget.refresh.MSwipeRefreshLayout;
import com.drinks.yiniang.utils.ToastUtils;
import com.hansen.library.Constants;
import com.hansen.library.io.tuple.Tuple2;
import com.hansen.library.listener.APIRequestCallback;
import com.hansen.library.ui.fragment.BaseLazyFragment;
import com.hansen.library.utils.ArithmeticUtil;
import com.hansen.library.utils.CommonUtils;
import com.hansen.library.utils.StringUtils;

import java.util.ArrayList;

/**
 * 他人用户社区-分享
 * Created by han on 2019/11/20
 * A simple {@link Fragment} subclass.
 */
public class UCShareFragment extends BaseLazyFragment implements SwipeRefreshLayout.OnRefreshListener, BaseQuickAdapter.OnItemClickListener,
        BaseQuickAdapter.OnItemChildClickListener, CommentBoxDialog.OnSendCommentListener, BaseQuickAdapter.RequestLoadMoreListener {

    //refresh
    private MSwipeRefreshLayout refresh_uc_share;
    private BaseRecyclerView rcv_uc_share;

    private CommentBoxDialog mCommentBoxDialog;

    private UCShareAdapter mUcShareAdapter;

    //查看的用户id
    private String mUserId;

    private int mPages;

    public UCShareFragment() {
        // Required empty public constructor
    }

    public static UCShareFragment newInstance(String userId) {

        Bundle bundle = new Bundle();
        bundle.putString(Constants.KeyUserId, userId);

        UCShareFragment fragment = new UCShareFragment();
        fragment.setArguments(bundle);

        return fragment;
    }

    @Override
    protected int getResID() {
        return R.layout.fragment_ucshare;
    }

    @Override
    protected void initView(View mView) {
        refresh_uc_share = mView.findViewById(R.id.refresh_uc_share);

        rcv_uc_share = mView.findViewById(R.id.rcv_uc_share);
    }

    @Override
    protected void initData() {
        mContext = getActivity();

        mUserId = getArguments() != null ? getArguments().getString(Constants.KeyUserId) : null;

        initAdapter();
    }

    private void initAdapter() {
        rcv_uc_share.setLayoutManager(new LinearLayoutManager(mContext));
        rcv_uc_share.addItemDecoration(ItemSpacesDecoration.getItemDPDecoration(10));

        mUcShareAdapter = new UCShareAdapter(mContext, new ArrayList<CommunityNewsJson.CommunityNewsList>());
        mUcShareAdapter.setCommonEmpty(getLayoutInflater(), rcv_uc_share);
        mUcShareAdapter.bindToRecyclerView(rcv_uc_share);
    }

    @Override
    protected void listener() {
        refresh_uc_share.setOnRefreshListener(this);
        mUcShareAdapter.setOnItemClickListener(this);
        mUcShareAdapter.setOnItemChildClickListener(this);
        mUcShareAdapter.setOnLoadMoreListener(this, rcv_uc_share);
    }

    @Override
    protected void widgetClick(View v) {

    }

    @Override
    protected void lazyLoadData() {
        getCommunityNews();
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

    }

    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        if(!ActivityUtils.isLogined(this, mContext, true)) {
            return;
        }

        CommunityNewsJson.CommunityNewsList data = mUcShareAdapter.getItem(position);

        if(data == null) {
            return;
        }

        switch (view.getId()) {
            case R.id.iv_uc_share_three_dot://分享
                ShareDialog dialog = ShareDialog.newInstance(data.getFans_id(), data.getId(), true, true);

                dialog.show(getChildFragmentManager(), Constants.TAG_SHARE_DIALOG);
                break;
            case R.id.tv_uc_share_collect://收藏
                doCollect(data, position);
                break;
            case R.id.tv_uc_share_like://点赞
                doLike(data, position);
                break;
            case R.id.tv_uc_share_total_comments://总评论
                Intent intent = new Intent(mContext, CommunityCommentsActivity.class);
                intent.putExtra(Constants.KeyCommunityId, data.getId());
                startActivity(intent);
                break;
            case R.id.tv_uc_share_comments_add://评论
                mCommentBoxDialog = CommentBoxDialog.newInstance(position);
                mCommentBoxDialog.show(getChildFragmentManager(), Constants.TAG_COMMENTS_DIALOG);
                break;
                default:
                    break;
        }
    }

    @Override
    public void onRefresh() {
        getCommunityNews();
    }

    @Override
    public void sendComment(String comment, final int position) {
        CommunityNewsJson.CommunityNewsList data = mUcShareAdapter.getItem(position);

        if (data == null || StringUtils.isEmpty(data.getId())) {
            return;
        }

        if (StringUtils.isEmpty(comment)) {
            return;
        }

        showLoadingDialog();

        CommunityApiIO.getInstance().doCommunityComments(data.getId(), comment, null,
                new APIRequestCallback<CommentSubmitJson, Tuple2<Integer, String>>() {
                    @Override
                    public void onSuccess(CommentSubmitJson res) {
                        if(mCommentBoxDialog != null) {
                            mCommentBoxDialog.dismiss();
                        }

                        CommunityNewsJson.CommunityNewsList data = mUcShareAdapter.getItem(position);

                        if(data == null) {
                            return;
                        }

                        if(data.getComment() == null) data.setComment(new ArrayList<CommunityNewsJson.CommunityNewsComment>());

                        if(data.getComment().size() >= 2) {
                            for(int i = data.getComment().size() - 1; i >= 0; i--) {
                                if(i >= 1) {
                                    data.getComment().remove(i);
                                }
                            }
                        }

                        CommunityNewsJson.CommunityNewsComment commentData = new CommunityNewsJson.CommunityNewsComment();
                        commentData.setCommunity_id(res.getData().getCommunity_id());
                        commentData.setContent(res.getData().getContent());
                        commentData.setId(res.getData().getId());
                        commentData.setNickname(res.getData().getNickname());

                        data.setComment_count(ArithmeticUtil.add(data.getComment_count(), 1));
                        data.getComment().add(0, commentData);

                        mUcShareAdapter.setData(position, data);
                    }

                    @Override
                    public void onError(Tuple2<Integer, String> error) {
                        ToastUtils.showShort(error._2);
                    }

                    @Override
                    public void onComplete() {
                        dismissDialog();
                    }
                });
    }

    @Override
    public void onLoadMoreRequested() {
        CommunityApiIO.getInstance().getOtherCommunityNews(mUserId, mPages, new APIRequestCallback<CommunityNewsJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(CommunityNewsJson res) {
                if (mUcShareAdapter == null) {
                    return;
                }

                mPages++;

                mUcShareAdapter.addData(res.getData().getData());

                if (CommonUtils.isHasMoreData(res.getData().getData())) {
                    mUcShareAdapter.loadMoreComplete();
                } else {
                    mUcShareAdapter.loadMoreEnd();
                }
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                ToastUtils.showShort(error._2);
            }

            @Override
            public void onComplete() {
            }
        });
    }

    //获取社区动态
    private void getCommunityNews() {
        if (StringUtils.isEmpty(mUserId)) {
            refresh_uc_share.setRefreshing(false);
            ToastUtils.showShort(R.string.text_user_not_exist);
            return;
        }

        if(!refresh_uc_share.isRefreshing()) {
            showLoadingDialog();
        }

        mPages = 1;

        CommunityApiIO.getInstance().getOtherCommunityNews(mUserId, mPages, new APIRequestCallback<CommunityNewsJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(CommunityNewsJson res) {
                if (mUcShareAdapter == null) {
                    return;
                }

                mPages++;

                mUcShareAdapter.getData().clear();
                mUcShareAdapter.addData(res.getData().getData());

                if (CommonUtils.isHasMoreData(res.getData().getData())) {
                    mUcShareAdapter.loadMoreComplete();
                } else {
                    mUcShareAdapter.loadMoreEnd();
                }
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                ToastUtils.showShort(error._2);
            }

            @Override
            public void onComplete() {
                refresh_uc_share.setRefreshing(false);
                dismissDialog();
            }
        });
    }

    private void doLike(final CommunityNewsJson.CommunityNewsList data, final int pos) {
        if (StringUtils.isEmpty(data.getId())) {
            ToastUtils.showShort(R.string.text_community_not_exist);
            return;
        }

        showLoadingDialog();

        CommunityApiIO.getInstance().doCommunityLike(data.getId(), new APIRequestCallback<StringJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(StringJson res) {
                if(CommonUtils.isArrayIndexOutOfBounds(mUcShareAdapter.getData(), pos)) {
                    return;
                }

                data.setLike_count(res.getData());
                data.setIs_like(Constants.STATUS_GLOBAL_YES.equals(data.getIs_like()) ? Constants.STATUS_GLOBAL_NO : Constants.STATUS_GLOBAL_YES);

                mUcShareAdapter.setData(pos, data);
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                ToastUtils.showShort(error._2);
            }

            @Override
            public void onComplete() {
                dismissDialog();
            }
        });
    }

    private void doCollect(final CommunityNewsJson.CommunityNewsList data, final int pos) {
        if (StringUtils.isEmpty(data.getId())) {
            ToastUtils.showShort(R.string.text_community_not_exist);
            return;
        }

        showLoadingDialog();

        CommunityApiIO.getInstance().doCommunityCollect(data.getId(), new APIRequestCallback<StringJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(StringJson res) {
                if(CommonUtils.isArrayIndexOutOfBounds(mUcShareAdapter.getData(), pos)) {
                    return;
                }

                data.setCollect_count(res.getData());
                data.setIs_collect(Constants.STATUS_GLOBAL_YES.equals(data.getIs_collect()) ? Constants.STATUS_GLOBAL_NO : Constants.STATUS_GLOBAL_YES);

                mUcShareAdapter.setData(pos, data);
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                ToastUtils.showShort(error._2);
            }

            @Override
            public void onComplete() {
                dismissDialog();
            }
        });
    }
}
